/**
 * @author Eric Jahn Course: Object Oriented Programming Final Project Due Date:
 * August 3, 2012
 */
package oop.chat.gui;

import java.awt.Color;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import javax.swing.*;
import oop.chat.connection.Client;
import oop.chat.data.Message;
import oop.chat.search.Search;
import oop.chat.search.SearchType;
import oop.chat.user.*;

/**
 * gui for our chat program
 * @author Eric Jahn
 */
public class Gui extends JFrame
{
    //error color
    private static final Color ERROR_COLOR = new Color(255, 0, 0);
    //client instance for communication
    private Client client;
    //search object
    private Search search;
    private SearchType searchType;
    //list model for the jlist
    private DefaultListModel listModel;
    //number of elements in the contact menu
    private int contactMenuSize;
	
	private ArrayList<String> contactPIDs;
	private ArrayList<Integer> selectedRecipients;
	private ContactList currentContactList;
			
    /**
     * default constructor
     *
     * @param	host	String
     */
    public Gui(Client client)
    {
        super("OOP Final Project");

        this.client = client;
		this.setTitle(this.client.getUserAccount().getContactInfo().getFullName());

        this.search = null;
        this.contactMenuSize = 0;
		
		this.contactPIDs = new ArrayList<String>();
		this.selectedRecipients = new ArrayList<Integer>();
		this.currentContactList = null;

        //initialize gui --> generated function
        this.initComponents();

        //set options for dialog windows
        this.searchDialog.setSize(400, 450);
        this.searchDialog.setLocation(this.getSize().width / 2, this.getSize().height / 2);		
		this.addContactDialog.setSize(280, 270);
        this.addContactDialog.setLocation(this.getSize().width / 2, this.getSize().height / 2);
		this.addContactDialog.setTitle("Add a new contact");
        this.loginDialog.setSize(330, 115);
        this.loginDialog.setLocation(this.getSize().width / 2, this.getSize().height / 2);
		this.loginDialog.setTitle("Chat-Login");

        //diasble the log area
        this.messageLogArea.setEditable(false);

        //add mouse listener to jlist
        MouseListener mouseListener = new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                if (e.getClickCount() == 2)
                {
                    //get name of the contact
                    String selectedItem = (String)contactList.getSelectedValue();
                    //set recipient
                    String recipients = recipientField.getText();
                    if (recipients.length() == 0)
                    {
                        recipients = selectedItem;
                    }
                    else
                    {
                        recipients += ", " + selectedItem;
                    }
                    recipientField.setText(recipients);
					
					//safe index from item to retrieve the pid in the send action
					selectedRecipients.add(contactList.getSelectedIndex());
                }
            }
        };
        //add mouse listener to jlist
        this.contactList.addMouseListener(mouseListener);
        this.contactList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        //initialize listmodel
        this.listModel = new DefaultListModel();

        //initialize contact menu
        this.initMenu();
        //disable resizable function
        this.setResizable(false);
        this.setVisible(true);
		
		this.loginDialog.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchDialog = new javax.swing.JDialog();
        searchField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        searchResultArea = new javax.swing.JTextArea();
        addContactDialog = new javax.swing.JDialog();
        pidField = new javax.swing.JTextField();
        PIDLabel = new javax.swing.JLabel();
        firstnameLabel = new javax.swing.JLabel();
        firstnameField = new javax.swing.JTextField();
        lastnameField = new javax.swing.JTextField();
        lastnameLabel = new javax.swing.JLabel();
        yearField = new javax.swing.JTextField();
        yearLbael = new javax.swing.JLabel();
        programField = new javax.swing.JTextField();
        programLabel = new javax.swing.JLabel();
        addContactButton = new javax.swing.JButton();
        loginDialog = new javax.swing.JDialog();
        loginButton = new javax.swing.JButton();
        passwordField = new javax.swing.JPasswordField();
        errorLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        messageArea = new javax.swing.JTextArea();
        sendButton = new javax.swing.JButton();
        recipientField = new javax.swing.JTextField();
        jScrollPane3 = new javax.swing.JScrollPane();
        contactList = new javax.swing.JList();
        messageLogTabs = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        messageLogArea = new javax.swing.JTextArea();
        menu = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        closeMenuItem = new javax.swing.JMenuItem();
        contactMenu = new javax.swing.JMenu();
        addContactItem = new javax.swing.JMenuItem();
        searchMenu = new javax.swing.JMenu();

        searchDialog.setAlwaysOnTop(true);

        searchField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                searchFieldKeyPressed(evt);
            }
        });

        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        searchResultArea.setColumns(20);
        searchResultArea.setRows(5);
        jScrollPane4.setViewportView(searchResultArea);

        javax.swing.GroupLayout searchDialogLayout = new javax.swing.GroupLayout(searchDialog.getContentPane());
        searchDialog.getContentPane().setLayout(searchDialogLayout);
        searchDialogLayout.setHorizontalGroup(
            searchDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, searchDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(searchDialogLayout.createSequentialGroup()
                        .addComponent(searchField)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(searchButton))
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE))
                .addContainerGap())
        );
        searchDialogLayout.setVerticalGroup(
            searchDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(searchDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
                .addContainerGap())
        );

        addContactDialog.setAlwaysOnTop(true);

        PIDLabel.setText("PID:");

        firstnameLabel.setText("Firstname:");

        lastnameLabel.setText("Lastname:");

        yearLbael.setText("Year:");

        programLabel.setText("Program:");

        addContactButton.setText("Add Contact");
        addContactButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addContactButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout addContactDialogLayout = new javax.swing.GroupLayout(addContactDialog.getContentPane());
        addContactDialog.getContentPane().setLayout(addContactDialogLayout);
        addContactDialogLayout.setHorizontalGroup(
            addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addContactDialogLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(addContactButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addContactDialogLayout.createSequentialGroup()
                            .addComponent(PIDLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(pidField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addContactDialogLayout.createSequentialGroup()
                            .addComponent(yearLbael)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(yearField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addContactDialogLayout.createSequentialGroup()
                            .addComponent(programLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(programField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addContactDialogLayout.createSequentialGroup()
                            .addComponent(lastnameLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(lastnameField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addContactDialogLayout.createSequentialGroup()
                            .addComponent(firstnameLabel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(firstnameField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        addContactDialogLayout.setVerticalGroup(
            addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, addContactDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pidField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(PIDLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(firstnameLabel)
                    .addComponent(firstnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lastnameLabel)
                    .addComponent(lastnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(yearLbael)
                    .addComponent(yearField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(addContactDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(programLabel)
                    .addComponent(programField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(addContactButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        loginDialog.setAlwaysOnTop(true);

        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        passwordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                passwordFieldKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout loginDialogLayout = new javax.swing.GroupLayout(loginDialog.getContentPane());
        loginDialog.getContentPane().setLayout(loginDialogLayout);
        loginDialogLayout.setHorizontalGroup(
            loginDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(loginDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(loginDialogLayout.createSequentialGroup()
                        .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(loginButton))
                    .addComponent(errorLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        loginDialogLayout.setVerticalGroup(
            loginDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(loginDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(loginDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginButton)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(errorLabel)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        messageArea.setColumns(20);
        messageArea.setRows(5);
        messageArea.setBorder(null);
        jScrollPane1.setViewportView(messageArea);

        sendButton.setText("Send");
        sendButton.setActionCommand("send");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(contactList);

        messageLogArea.setColumns(20);
        messageLogArea.setRows(5);
        jScrollPane2.setViewportView(messageLogArea);

        messageLogTabs.addTab("Chat 1", jScrollPane2);

        fileMenu.setText("File");

        closeMenuItem.setText("Close");
        closeMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(closeMenuItem);

        menu.add(fileMenu);

        contactMenu.setText("Contacts");

        addContactItem.setText("Add Contact");
        addContactItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addContactItemActionPerformed(evt);
            }
        });
        contactMenu.add(addContactItem);

        menu.add(contactMenu);

        searchMenu.setText("Search");
        menu.add(searchMenu);

        setJMenuBar(menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(recipientField)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(messageLogTabs)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(messageLogTabs)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(recipientField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(sendButton, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * send action is called
     *
     * @param	evt	ActionEvent
     */
	private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
            // TODO add your handling code here:		
		String message = this.messageArea.getText();
		String recipients = this.recipientField.getText();
		boolean errorOccurred = false;

		//if the user has entered no message, mark the border
		if(message.length() == 0)
		{
			this.messageArea.setBorder(BorderFactory.createLineBorder(Gui.ERROR_COLOR));
			errorOccurred = true;
		}
		else
		{
			this.messageArea.setBorder(null);
		}

		//check if the user has specified one or more recipients
		if(recipients.length() == 0)
		{
			this.recipientField.setBorder(BorderFactory.createLineBorder(Gui.ERROR_COLOR));
			errorOccurred = true;
		}
		else
		{
			this.recipientField.setBorder(null);
		}

		//only send message if no error occurred
		if(errorOccurred == false)
		{
			//get all recipients
			StringTokenizer tokenizer = new StringTokenizer(recipients, ",");
			//clear input fields
			this.recipientField.setText("");
			this.messageArea.setText("");

			//send message to every recipient
			String PID;
			for(int i = 0; i < this.selectedRecipients.size(); ++i)
			{
				PID = this.contactPIDs.get(this.selectedRecipients.get(i));
				//[ send_message:pid, "message goes here" ]
				this.client.processMessage("send_message:" + PID + "," + message);

				//check if we need to create a new tab
				if(i > 1)
				{
					this.addTab();
				}

				//set title of the tab
				this.messageLogTabs.setTitleAt(i, tokenizer.nextToken().trim());

				Contact destination = this.client.getUserAccount().getContactLists()[i].getContact(PID);
				Message messageObject = new Message(message, this.client.getUserAccount(), destination);
				this.messageLogArea.append(messageObject.toString() + "\n");
			}
		}
	}//GEN-LAST:event_sendButtonActionPerformed

	private void closeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeMenuItemActionPerformed
		// TODO add your handling code here:
		//send disconnect request
		//this.client.processMessage(null);
		System.exit(0);
	}//GEN-LAST:event_closeMenuItemActionPerformed

	private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
		this.performSearch();
	}//GEN-LAST:event_searchButtonActionPerformed

    /**
     * add the new contact to the contact list of the user
     *
     * @param	evt	ActionEvent
	 */
	private void addContactButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addContactButtonActionPerformed
		// TODO add your handling code here:
		Contact newContact = new Contact(this.pidField.getText(),
			this.firstnameField.getText(),
			this.lastnameField.getText(),
			this.yearField.getText(),
			this.programField.getText());
		
		//add contact to the list
		this.client.getUserAccount().addContact(newContact);
		this.displayContacts(this.client.getUserAccount().getContactListByCategory(Category.COMMON_LIST));
		//hide dialog window
		this.addContactDialog.setVisible(false);
	}//GEN-LAST:event_addContactButtonActionPerformed

	/**
	 * opens the add contact dialog window
	 * @param	evt			ActionEvent
	 */
	private void addContactItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addContactItemActionPerformed
		// TODO add your handling code here:
		this.addContactDialog.setVisible(true);
	}//GEN-LAST:event_addContactItemActionPerformed

	/**
	 * the user has entered his password, so try to login him into the chat
	 * @param	evt			ActionEvent
	 */
	private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
		// TODO add your handling code here:
		this.performLogin();
	}//GEN-LAST:event_loginButtonActionPerformed

	/**
	 * perform search action after the user pressed enter
	 * @param	evt			KeyEvent
	 */
	private void searchFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchFieldKeyPressed
		// TODO add your handling code here:
		//get code of the key
		int key = evt.getKeyCode();
		//if the enter key was hit, perform action
        if (key == KeyEvent.VK_ENTER)
		{
			this.performSearch();
		}
	}//GEN-LAST:event_searchFieldKeyPressed

	/**
	 * perform login action after the user pressed enter
	 * @param	evt			KeyEvent
	 */
	private void passwordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldKeyPressed
		// TODO add your handling code here:
		//get code of the key
		int key = evt.getKeyCode();
		//if the enter key was hit, perform action
        if (key == KeyEvent.VK_ENTER)
		{
			this.performLogin();
		}
	}//GEN-LAST:event_passwordFieldKeyPressed

	/**
	 * initialize the menu, create contact list and search menu
	 */
    private void initMenu()
    {
		UserAccount user = this.client.getUserAccount();
        if(user != null)
        {
			ContactList[] contactLists = user.getContactLists();
			for (ContactList item : contactLists)
			{
				if(!item.isListEmpty())
				{
					//System.out.println(contactLists.get(i).getClass());
					JMenuItem newMenuItem;
					//determine the type of the list
					if(item instanceof SpecialList)
					{
						//special contact list
						newMenuItem = new JMenuItem(((SpecialList) item).getCategory().getMenuLabel());
					}
					else
					{
						//common contact list
						newMenuItem = new JMenuItem(Category.COMMON_LIST.getMenuLabel());
						//this is the default list --> display their contacts
						this.displayContacts(item);
						this.currentContactList = item;
						newMenuItem.setEnabled(false);
					}

					//add the contact list as a property to the menu item
					newMenuItem.putClientProperty(newMenuItem.getText(), item);
					//add action listener to the item
					newMenuItem.addActionListener(new ContactAction(this));
					//finally add the item to the menu
					this.contactMenu.add(newMenuItem);
					++this.contactMenuSize;
				}
			}
        }

        //create search menu
        for (SearchType type : SearchType.values())
        {
            //create menu item with label, add action listener and client property
            JMenuItem newMenuItem = new JMenuItem(type.getMenuLabel());
            newMenuItem.putClientProperty(newMenuItem.getText(), type);
            newMenuItem.addActionListener(new SearchAction(this));
            this.searchMenu.add(newMenuItem);
        }
    }

    /**
     * action performed method for contactlist menu items when the user has
     * selected one list, all contacts will be displayed in the jlist on the
     * left site
     *
     * @param	e	ActionEvent
     */
    public void contactActionPerformed(ActionEvent e)
    {
        //get source
        JMenuItem item = (JMenuItem)e.getSource();
        //get the actual contact list information from the item
        ContactList list = (ContactList)item.getClientProperty(e.getActionCommand());

        //reset enebale status of all menu items
        for (int i = 0; i < this.contactMenuSize; ++i)
        {
            this.contactMenu.getItem(i).setEnabled(true);
        }

        //disable the last selected item
        item.setEnabled(false);

        //finally dispaly the contacts
		this.currentContactList = list;
        this.displayContacts(list);
    }

    /**
     * create the list of contacts in the jlist
     *
     * @param	list	ContactList
     */
    private void displayContacts(ContactList list)
    {
        int index = 0;
        HashMap<String, Contact> contacts = list.getUserContacts();
        //reset listmodel and contact pids
        this.listModel.removeAllElements();
		this.contactPIDs.clear();
        //iterate through every contact in the list
        for (Contact contact : contacts.values())
        {
            this.listModel.add(index, contact.getFullName());
			this.contactPIDs.add(contact.getPID());
            ++index;
        }
        //add model to the jlist
        this.contactList.setModel(this.listModel);
    }
	
	public void displayNewMessage(Message message)
	{
		this.messageLogArea.append(message.toString() + "\n");
	}

    /**
     * initializes a new search
     *
     * @param	e	ActionEvent
     */
    public void searchActionPerformed(ActionEvent e)
    {
        //display the dialog box
        this.searchDialog.setTitle(e.getActionCommand() + "-Search");
        this.searchDialog.setVisible(true);
        //safe search type
        JMenuItem item = (JMenuItem)e.getSource();
        this.searchType = (SearchType)item.getClientProperty(e.getActionCommand());
    }

	/**
	 * adds a new chat tab
	 */
    private void addTab()
    {
        JTextArea newTextArea = new JTextArea();
        JScrollPane newScrollPane = new JScrollPane();
        newTextArea.setColumns(20);
        newTextArea.setRows(5);
        newScrollPane.setViewportView(newTextArea);
        this.messageLogTabs.addTab(null, newScrollPane);
    }
	
	/**
	 * main function to perform a new search
	 */
	private void performSearch()
	{
		// TODO add your handling code here:
		UserAccount user = this.client.getUserAccount();
		String searchword = this.searchField.getText();
		if (searchword.length() != 0) 
		{
			//create search object
			this.search = this.searchType.getSearch();

			ArrayList<Contact> result = (ArrayList<Contact>) this.search.doSearch(searchword, user);
			if(result.size() > 0)
			{
				this.searchResultArea.append(result.toString() + "\n");
			}
			else
			{
				this.searchResultArea.append("The search for \"" + searchword + "\" returned 0 results.\n");
			}
			this.searchField.setText("");
		}
		//close dialog
		//this.searchDialog.dispose();
		//reset search type
		//this.searchType = null;
	}
	
	/**
	 * main function to perform the login
	 */
	private void performLogin()
	{
		String password = new String(this.passwordField.getPassword());
		//send password to server
		this.client.processMessage("login:" + password);
		//this code block could be better done with syncronized threads or an access lock
		try {
			Thread.sleep(500);
		}
		catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		if(this.client.getUserAccount().isLoggedIn())
		{
			this.loginDialog.setVisible(false);
		}
		else
		{
			this.passwordField.setBorder(BorderFactory.createLineBorder(Gui.ERROR_COLOR));
			this.errorLabel.setText("The provided password is incorrect. Please try again.");
		}
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel PIDLabel;
    private javax.swing.JButton addContactButton;
    private javax.swing.JDialog addContactDialog;
    private javax.swing.JMenuItem addContactItem;
    private javax.swing.JMenuItem closeMenuItem;
    private javax.swing.JList contactList;
    private javax.swing.JMenu contactMenu;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JTextField firstnameField;
    private javax.swing.JLabel firstnameLabel;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextField lastnameField;
    private javax.swing.JLabel lastnameLabel;
    private javax.swing.JButton loginButton;
    private javax.swing.JDialog loginDialog;
    private javax.swing.JMenuBar menu;
    private javax.swing.JTextArea messageArea;
    private javax.swing.JTextArea messageLogArea;
    private javax.swing.JTabbedPane messageLogTabs;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField pidField;
    private javax.swing.JTextField programField;
    private javax.swing.JLabel programLabel;
    private javax.swing.JTextField recipientField;
    private javax.swing.JButton searchButton;
    private javax.swing.JDialog searchDialog;
    private javax.swing.JTextField searchField;
    private javax.swing.JMenu searchMenu;
    private javax.swing.JTextArea searchResultArea;
    private javax.swing.JButton sendButton;
    private javax.swing.JTextField yearField;
    private javax.swing.JLabel yearLbael;
    // End of variables declaration//GEN-END:variables
}